package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ExaminationAnswerSheetComDO;
import com.jinzhi.jzweb.domain.ExaminationResultsComDO;
import com.jinzhi.jzweb.pojo.StuSignUpTeamVo;
import com.jinzhi.jzweb.pojo.StuVo;
import com.jinzhi.jzweb.service.ExaminationAnswerSheetComService;
import com.jinzhi.jzweb.service.ExaminationResultsComService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.ZipFileUtils;
import com.jinzhi.oss.controller.FileController;
import org.apache.commons.lang.StringUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.StuSignUpComDao;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.service.StuSignUpComService;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.stream.Collectors;


/**
 *
 * <pre>
 * 考生报名
 * </pre>
 * <small> 2023-05-05 08:52:02 | lance</small>
 */
@Service
public class StuSignUpComServiceImpl extends CoreServiceImpl<StuSignUpComDao, StuSignUpComDO> implements StuSignUpComService {


    @Override
    public List<StuSignUpTeamVo> sumTeamStuSignExam(String name) {
        return baseMapper.sumTeamStuSignExam( name);
    }

    @Override
    public List<StuSignUpTeamVo> sumOneStuSignExam(String name) {
        return baseMapper.sumOneStuSignExam(name);
    }

    private final ExaminationResultsComService examinationResultsComService;

    private final ExaminationAnswerSheetComService examinationAnswerSheetComService;

    private final DictService dictService;

    private final FileController fileController;

    @Override
    public Integer MaxNum(Long cbatchId) {
        return baseMapper.MaxNum(cbatchId);
    }


    public StuSignUpComServiceImpl(ExaminationResultsComService examinationResultsComService,ExaminationAnswerSheetComService examinationAnswerSheetComService,
                                   DictService dictService,FileController fileController) {
        this.examinationResultsComService = examinationResultsComService;
        this.examinationAnswerSheetComService = examinationAnswerSheetComService;
        this.dictService = dictService;
        this.fileController = fileController;
    }

    @Override
    public Page<StuSignUpComDO> getStuGignUpCom(Integer curr,Integer pageSize) {
        Page<StuSignUpComDO> page = new Page<>(
                Optional.of(curr).orElse(1),
                Optional.of(pageSize).orElse(10));
        //查询全部考生信息
        Page<StuSignUpComDO> sign = selectPage(page,new EntityWrapper<StuSignUpComDO>());
        //获取考生三个赛场得分
        //根据学生id查询成绩
        ExaminationResultsComDO examinationResultsComDO = new ExaminationResultsComDO();
        for (StuSignUpComDO stuSignUpComDO:sign.getRecords()){
            examinationResultsComDO.setStuSignId(stuSignUpComDO.getId());
            ExaminationResultsComDO rcd = examinationResultsComService.selectOne(examinationResultsComDO);
            if(rcd!=null) {

                Double a111 = ((rcd.getScoingb1() + rcd.getScoingb2() + rcd.getScoingb3())/3);
                a111 = a111 + (rcd.getTotalScore()); //理论成绩
                BigDecimal a1 = new BigDecimal(a111);
                double a11 = a1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                rcd.setScoreA(String.valueOf(a11));

                BigDecimal b1 = new BigDecimal(((rcd.getScore1() + rcd.getScore2() + rcd.getScore3())/3));
                double b11 = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                rcd.setScoreB(String.valueOf(b11));

                BigDecimal c1 = new BigDecimal(((rcd.getScoingc1() + rcd.getScoingc2() + rcd.getScoingc3())/3));
                double c11 = c1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                rcd.setScoreC(String.valueOf(c11));

                stuSignUpComDO.setScore(Double.valueOf(rcd.getScoreA())+Double.valueOf(rcd.getScoreB())+Double.valueOf(rcd.getScoreC()));
                stuSignUpComDO.setExaminationResultsComDO(rcd);
            }
        }
        page.setRecords(sign.getRecords().stream().sorted(Comparator.comparing(StuSignUpComDO::getScore,Comparator.nullsFirst(Double::compareTo)).reversed()).collect(Collectors.toList()));
        return page;
    }

    public List<StuSignUpComDO> forDes(List<StuSignUpComDO> list1){
        if(list1.size()==0){
            return new ArrayList<>();
        }
        for (int i = 0; i < list1.size(); i++) {
            list1.get(i).setDes(i+1);
        }
        return list1;
    }



    @Override
    public void stuGignUpCom(HttpServletResponse response) {
        List<StuVo> stuVos = new ArrayList<>();
        //查询全部考生信息
        List<StuSignUpComDO> sign = selectList(new EntityWrapper<StuSignUpComDO>().eq("decrypt",1));
        //获取考生三个赛场得分
        //根据学生id查询成绩
        ExaminationResultsComDO examinationResultsComDO = new ExaminationResultsComDO();
        sign.forEach(a ->{
            StuVo stuVo = new StuVo();
            examinationResultsComDO.setStuSignId(a.getId());
            ExaminationResultsComDO rcd = examinationResultsComService.selectOne(examinationResultsComDO);
            if(rcd!=null) {

                Double a111 = ((rcd.getScoingb1() + rcd.getScoingb2() + rcd.getScoingb3())/3);
                a111 = a111 + (rcd.getTotalScore()); //理论成绩
                BigDecimal a1 = new BigDecimal(a111);
                double a11 = a1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                rcd.setScoreA(String.valueOf(a11));

                BigDecimal b1 = new BigDecimal(((rcd.getScore1() + rcd.getScore2() + rcd.getScore3())/3));
                double b11 = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                rcd.setScoreB(String.valueOf(b11));

                BigDecimal c1 = new BigDecimal(((rcd.getScoingc1() + rcd.getScoingc2() + rcd.getScoingc3())/3));
                double c11 = c1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                rcd.setScoreC(String.valueOf(c11));

                a.setScore(Double.valueOf(rcd.getScoreA())+Double.valueOf(rcd.getScoreB())+Double.valueOf(rcd.getScoreC()));
                a.setExaminationResultsComDO(rcd);

                stuVo.setScoreA(String.valueOf(a11));
                stuVo.setScoreB(String.valueOf(b11));
                stuVo.setScoreC(String.valueOf(c11));
            }
            stuVo.setNum2(a.getNum2());
            stuVo.setRealityUm2(a.getCandidateNumber());
            stuVo.setName(a.getName());
            stuVo.setIdNumber(a.getIdNumber());
            stuVo.setUnitName(a.getUnitName());
            stuVo.setTeacher(a.getTeacher());
            stuVo.setComNums(a.getComNums());
            stuVos.add(stuVo);

        });
        sign.stream().sorted(Comparator.comparing(StuSignUpComDO::getScore,Comparator.nullsFirst(Double::compareTo)).reversed()).collect(Collectors.toList());
        //导出操作
        EasyPoiUtil.exportExcel(stuVos, "选手解密导出", "选手解密导出", StuVo.class, "选手解密导出", response);
    }

    @Override
    public Result stuFileDownload(HttpServletResponse response) {
        //获取批次名称
//        String baName =  examinationBatchService.selectById(cbatchId).getName();
        String baName = "A赛场理论考试制定照护计划导出";
        //根据赛场id获取考生信息
        List<StuSignUpComDO> signs = this.selectList(new EntityWrapper<>());
        if(signs.isEmpty()){
            return Result.fail("考生信息为空");
        }
        List<Long> stuIds = signs.stream().map(StuSignUpComDO::getId).collect(Collectors.toList());
        //根据考生id集合获取考生文件链接
        List<ExaminationAnswerSheetComDO> exs = examinationAnswerSheetComService.selectList(new
                EntityWrapper<ExaminationAnswerSheetComDO>().in("stu_sign_id",stuIds));
        //筛选出有附件的考生答卷
        List<ExaminationAnswerSheetComDO> files = exs.stream().filter(a -> !StringUtils.isBlank(a.getFile())).distinct().collect(Collectors.toList());
        if(files.isEmpty()){
            return Result.fail("没有可下载的附件");
        }
        //添加二次加密号
        files.forEach(a -> signs.forEach(b ->{
            if(Objects.equals(a.getStuSignId(),b.getId())){
                a.setNum2(b.getNum2());
            }
        }));
        Map<String, String> map =new HashMap<>();
        map.put("type","foundZip");
        map.put("name","foundZip");
        String foundZip = dictService.selDicBy(map);
        //调用文件接口

        return Result.ok(foundZip(files,baName,response,foundZip));
    }

    /**
     * 封装文件接口
     */
    private String foundZip(List<ExaminationAnswerSheetComDO> files,String baName,HttpServletResponse response,String foundZip){
        try {
            List<File> file = new ArrayList<>();
            for (int j = 0; j < files.size(); j++) {
                URL url = new URL(files.get(j).getFile());
                String fileName = url.getFile();
                // 打开到该URL的连接
                URLConnection conn = url.openConnection();
                // 从连接中获取输入流
                InputStream in = conn.getInputStream();
                // 创建一个临时文件来存储下载的映像
//                Date date = new Date();
//                String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
                String substring = "";
                if(fileName.lastIndexOf('.')>0){
                    substring = fileName.substring(fileName.lastIndexOf("."));
                }
                File tempFile = File.createTempFile(files.get(j).getNum2()+ "_" , substring);
                // 创建一个输出流，将映像写入临时文件
                FileOutputStream out = new FileOutputStream(tempFile);
                // 从输入流中读取文件并将其写入输出流
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                // 关闭输入和输出流
                in.close();
                out.close();
                // 打印临时文件的路径
                System.out.println("Downloaded file saved as "+tempFile.getAbsolutePath());
                File file1  = new File(tempFile.getAbsolutePath());
                file.add(file1);

            }
            String fileName = foundZip + baName + ".zip";
            System.out.println("Downloaded Zip saved as"+fileName);
            //压缩文件
            ZipFileUtils.generateZip(new File(fileName), file, false);
            //下载文件
            //ZipFileUtils.download(new File(fileName),response);
            //ZipFileUtils.downloadZip(new File(fileName),response);
            //把临时文件上传至服务器
            File filess = new File(fileName);
            MultipartFile cMultiFile = new MockMultipartFile("file", filess.getName(), null, new FileInputStream(filess));
            //上传成功后删除临时文件
            filess.delete();
            return fileController.upload(cMultiFile).getData();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {

        }
    }

}
